package com.codeying.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 常用工具类
 */
public class CommonUtils {

    public static final String fileUploadPath = "d:/课设文件上传目录/";

    static {
        //创建上传文件的文件夹
        System.out.println(fileUploadPath);
        File file = new File(fileUploadPath);
        if(!file.exists()){
            file.mkdirs();
        }
    }

    /**
     * 把request转为map
     */
    public static Map<String,Object> requestToMap(HttpServletRequest req){
        //1 先判断上传的数据是否多段数据（只有是多段的数据，才是文件上传的）
        if (ServletFileUpload.isMultipartContent(req)) {
            Map<String,Object> map = new HashMap<>();
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                // 解析上传的数据，得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                // 循环判断，每一个表单项，是普通类型，还是上传的文件
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        // 普通表单项,不存在key时添加，存在则不再覆盖！
                        if(!map.containsKey(fileItem.getFieldName())){
                            System.out.println("key：" + fileItem.getFieldName()+",value:" + fileItem.getString("UTF-8"));
                            map.put(fileItem.getFieldName(),fileItem.getString("UTF-8"));
                        }
                    } else {
                        // 上传文件
                        String fileName = handleFileName(fileItem.getName());
                        //处理文件名
                        System.out.println("文件：" + fileItem.getFieldName()+",value:" + fileName);
                        fileItem.write(new File(fileUploadPath + fileName));
                        //减去最后面的File
                        map.put(fileItem.getFieldName().substring(0,fileItem.getFieldName().length()-4),fileName);
                    }
                }
            } catch (Exception e) {
                System.out.println("CommonUtils-> requestToMap 发生错误！");
                e.printStackTrace();
                System.out.println("CommonUtils-> requestToMap 发生错误！");
            }
            return map;
        }else {
            return getParameterMap(req);
        }
    }

    /**
     * 把request转为map
     */
    private static Map<String, Object> getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map<?, ?> properties = request.getParameterMap();
        // 返回值Map
        Map<String, Object> returnMap = new HashMap<>();
        Iterator<?> entries = properties.entrySet().iterator();

        Map.Entry<String, Object> entry;
        String name = "";
        String value = "";
        Object valueObj =null;
        while (entries.hasNext()) {
            entry = (Map.Entry<String, Object>) entries.next();
            name = (String) entry.getKey();
            valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    private static int n = 10000000;

    /**
     * 获取随机id，根据时间和五位随机数
     * @return
     */
    public static String getRandomIdByTime() {
        SimpleDateFormat simpleDateFormat;
        simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String str = simpleDateFormat.format(date);
        n++;
        if(n> (1<<26) ){
            n=10000000;
        }
        return str+n;
    }
    //获取Id
    public static int newId(){
        return Integer.parseInt(getRandomIdByTime());
    }

    /**
     * 替换文件名的非法字符
     * @param fileName
     * @return
     */
    public static String handleFileName(String fileName){
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        fileName = fileName.substring(0,fileName.lastIndexOf("."));
        String illegalChar = "!@#%&-=;':\"`~,/<>";
        for (int i = 0; i < illegalChar.length(); i++) {
            fileName = fileName.replaceAll(String.valueOf(illegalChar.charAt(i)),"");
        }
        fileName = fileName.replaceAll("\\(","");
        fileName = fileName.replaceAll("\\$","");
        fileName = fileName.replaceAll("\\)","");
        fileName = fileName.replaceAll("\\.","");
        fileName = fileName.replaceAll("\\*","");
        fileName = fileName.replaceAll("\\^","");
        fileName = fileName.replaceAll("\\+","");
        fileName = fileName.replaceAll("\\{","");
        fileName = fileName.replaceAll("\\}","");
        fileName = fileName.replaceAll("\\[","");
        fileName = fileName.replaceAll("\\]","");
        fileName = fileName.replaceAll("\\?","");
        if(fileName.equals("")){
            fileName = "picture";
        }
        return fileName + fileType;
    }
}


